package organization

import (
	"fmt"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/admin"
	"gq_volunteer_platform/model/organization"

	"github.com/gin-gonic/gin"
)

func MyMapDetail(c *gin.Context) {
	// 获取登录用户对象
	var adm admin.Admin
	if err := adm.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}
	var one organization.Organization

	if err := bean.MysqlDb.Where("id=?", adm.OrganizationId).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("机构不存在id:%d", adm.OrganizationId))
		return
	}

	c.PureJSON(200, one)

}

func MyMapEdit(c *gin.Context) {
	// 获取登录用户对象
	var adm admin.Admin
	if err := adm.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	var req struct {
		ResponsiblePerson      string  `binding:"max=255"`
		ResponsiblePersonPhone string  `binding:"max=255"`
		Address                string  `binding:"max=255"`
		Longitude              float64 `binding:"max=10000"`
		Latitude               float64 `binding:"max=10000"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one organization.Organization

	if err := bean.MysqlDb.Where("id=?", adm.OrganizationId).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("机构不存在id:%d", adm.OrganizationId))
		return
	}

	var two organization.Organization
	two.ID = one.ID
	two.ResponsiblePerson = req.ResponsiblePerson
	two.ResponsiblePersonPhone = req.ResponsiblePersonPhone
	two.Address = req.Address
	two.Longitude = req.Longitude
	two.Latitude = req.Latitude

	if err := bean.MysqlDb.Select("responsible_person", "responsible_person_phone", "address", "longitude", "latitude").Updates(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, "数据库错误")
		return
	}

	c.String(200, "ok")
}

func Map(c *gin.Context) {

	var list []struct {
		ID   uint
		Name string
		// ResponsiblePerson      string
		// ResponsiblePersonPhone string
		// Address                string
		Longitude float64
		Latitude  float64
	}

	var tx = bean.MysqlDb.Model(&organization.Organization{})

	// 查询列表
	if err := tx.Where("`latitude` <> 0 AND `Longitude` <> 0").Order("`sort` ASC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"list": list,
	})

}
